package com.kehutong.common;

import com.kehutong.common.util.Token;
import org.coraframework.authz.util.CookieUtils;
import org.coraframework.inject.Inject;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.util.Objects;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取Token信息
 *
 * @author: liukunlong
 * @date: 2021-04-21 09:28
 */
@Singleton
public class TokenService {

    private static final Logger logger = LoggerFactory.getLogger(TokenService.class);

    @Inject
    private DoveClient doveClient;

    /**
     * 获取用户Token信息
     * @param req
     * @return
     * @throws Exception
     */
    public Token getUserToken(HttpServletRequest req) throws Exception {
        String cookieId = CookieUtils.getCookieValue(req);
        if (Objects.isEmpty(cookieId)) {
            logger.error("TokenService.getUserToken is error,获取不到cookieId");
            return null;
        }

        JSONObject rs = doveClient.post("/kht-bin/session/service/get", http -> http.addParam("sessionId", cookieId));
        if (rs.getInteger("code") != 200) {
            logger.error("getToken fail: {}", rs.getString("message"));
            return null;
        }
        return Token.fromJSON(rs.getJSONObject("data"));
    }
}
